﻿(function ($) {
    //Creamos el mapeo de las vocales con sus acentos para las busquedas en los campos y poder omitir los acentos
    var accentMap = { "á": "a", "é": "e", "í": "i", "ó": "o", "ú": "u", "Á": "A", "É": "E", "Í": "I", "Ó": "O", "Ú": "U" };

    //Funcions que normaliza la palabra sin ningun acento, ya se mayuscula o minuscula
    var fxNormalizarString = function (term) {
        var ret = "";
        for (var i = 0; i < term.length; i++) {
            ret += accentMap[term.charAt(i)] || term.charAt(i);
        }
        return ret;
    };

    $.fn.fxAC = function (opt, events) {
        var $self = this;
        //Establecemos los valores por defecto
        fxAC_opt_def = { autoFocus: true, minParam: 1, fuente: null, dependiente: false, field: '' };
        fxAC_events_def = {selectEvent: '', focusEvent: ''};
        var fxACParam_Events = jQuery.extend(fxAC_events_def, events);
        var fxACParam_Opt = jQuery.extend(fxAC_opt_def, opt);

        $self.autocomplete({
            delay: 0,
            autoFocus: fxACParam_Opt.autoFocus,
            minLength: fxACParam_Opt.minParam,
            source: function (request, response) {
                var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                if (!fxACParam_Opt.dependiente) {
                    response($.grep(fxACParam_Opt.fuente, function (elm) {
                        value = elm.value || elm.label || elm;
                        return matcher.test(elm.label) || matcher.test(fxNormalizarString(elm.label));
                    }));
                } else {
                    var fieldDep = $(fxACParam_Opt.field).attr('depende');
                    var idD = $(fieldDep).val() || 0;
                    response($.grep(fxACParam_Opt.fuente[idD], function (elm) {
                        value = elm.value || elm.label || elm;
                        return matcher.test(elm.label) || matcher.test(fxNormalizarString(elm.label));
                    }));
                }
            },
            select: function (event, ui) {
                if (fxACParam_Events.selectEvent != "")
                    return fxACParam_Events.selectEvent();
            },
            focus: function (event, ui) {
                if (fxACParam_Events.focusEvent != "")
                    return fxACParam_Events.focusEvent();
            },
            change: function (event, ui) {
                var $self = $(this);
                var fieldID = $self.attr('acattr');
                if (ui.item) {
                    $self.val(ui.item.label);
                    $(fieldID).val(ui.item.value);
                } else {
                    $self.val('');
                    $(fieldID).val('0');
                }
            }
        });

    };

})(jQuery);